<template>
  <page-view class="page-view page-view-container" :title="false">
    <div slot="headerContent">
      <div class="title">角色管理</div>
    </div>

    <a-card v-permission:permission:menu class="s-card">
      <div class="filter">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="6" :sm="24">
                <a-form-item label="角色ID">
                  <a-input v-model="queryParam.code" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="角色名称">
                  <a-input v-model="queryParam.name" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="状态">
                  <a-select v-model="queryParam.status" placeholder="请选择" default-value="0">
                    <a-select-option value="0">全部</a-select-option>
                    <a-select-option value="1">启用</a-select-option>
                    <a-select-option value="2">禁止</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <span class="table-page-search-submitButtons">
                  <a-button class="primary-btn" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button v-permission:permission:add class="primary-btn" @click="handleCreate()">新建</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </div>

      <div class="table-container">
        <s-table
          ref="table"
          key="id"
          bordered
          :columns="user && user.permission && user.permission.includes('permission:update') ? columns : columnsBase"
          :data="loadDataWithPage"
          hide-on-single-page
          show-total
          show-quick-jumper
          class="pagination-container s-table"
        >
          <div
            slot="expandedRowRender"
            slot-scope="record"
            style="margin: 0"
          >
            <a-row
              :gutter="24"
              :style="{ marginBottom: '12px' }"
            >
              <a-col v-for="(pers, index) in record.permissions.byCate" :key="index" :span="12" :style="{ marginBottom: '12px' }">
                <a-col :lg="4" :md="24">
                  <span>{{ index }}：</span>
                </a-col>
                <a-col v-if="pers.length > 0" :lg="20" :md="24">
                  <a-tag v-for="(action, k) in pers" :key="k" color="cyan">{{ action }}</a-tag>
                </a-col>
                <a-col v-else :span="20">-</a-col>
              </a-col>
            </a-row>
          </div>
          <span slot="action" slot-scope="text, record">
            <a v-if="record && record.role && record.role.status" class="disabled-link no-padding" @click="toggleStatus(record)">禁用</a>
            <a v-else @click="toggleStatus(record)">启用</a>
            <a-divider type="vertical" />
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a class="danger-link no-padding" @click="clickDelete(record)">删除</a>
          <!-- <a-popconfirm
            title="将删除相关权限与角色关联,是否确认删除该角色？"
            ok-text="确认"
            cancel-text="取消"
            overlay-class-name="width-unset"
            @confirm="handleDelete(record)"
          >
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a href="javascript:;" style="color:red">删除</a>
          </a-popconfirm> -->

          </span>
        </s-table>

        <a-modal
          v-model="visible"
          title="操作"
          style="top: 20px;"
          :width="800"
          @ok="handleOk"
        >
          <a-form :form="form">

            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="唯一识别码"
              has-feedback
            >
              <a-input id="code" v-model="mdl.code" placeholder="唯一识别码" :disabled="!isCreate" />
            </a-form-item>

            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="角色名称"
              has-feedback
            >
              <a-input id="name" v-model="mdl.name" placeholder="起一个名字" />
            </a-form-item>

            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="状态"
              has-feedback
              :validate-status="mdl.status=='true'?'success':'warning'"
            >
              <a-select v-model="mdl.status">
                <a-select-option value="true">启用</a-select-option>
                <a-select-option value="false">禁用</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="描述"
              has-feedback
            >
              <a-textarea id="description" v-model="mdl.description" :rows="5" placeholder="..." />
            </a-form-item>

            <a-divider />

            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="拥有权限"
              has-feedback
            >
              <a-col v-for="(pers, index) in mdl.byCate" :key="index" :span="24" :style="{ marginBottom: '12px' }">
                <a-col :lg="6" :md="24">
                  <span>{{ index }}：</span>
                </a-col>
                <a-col v-if="pers.length > 0" :lg="18" :md="24">
                  <a-tag v-for="(action, k) in pers" :key="k" color="cyan">{{ action }}</a-tag>
                </a-col>
                <a-col v-else :span="18">-</a-col>
              </a-col>

            </a-form-item>
          </a-form>
        </a-modal>

        <a-modal
          v-model="showDelete"
          class="delete-modal"
          title="删除角色"
          centered
          ok-type="danger"
          @ok="handleDelete(deleteId)"
        >
          <div class="delete-text-content">
            <a-icon class="icon" theme="filled" type="warning" />
            <span>
              <span>确认删除所选角色？</span>
              <p style="color: red">注：请谨慎删除，删除角色后，关联角色的账号将失去角色的相关权限</p>
            </span>
          </div>
        </a-modal>

      </div>

    </a-card>
  </page-view>
</template>

<script>
import { STable, PageView } from '@/components'
import { mapState } from 'vuex'
// import moment from 'moment'

const columnsBase = [
  {
    title: '唯一识别码',
    dataIndex: 'role.code'
  },
  {
    title: '角色名称',
    dataIndex: 'role.name'
  },
  {
    title: '状态',
    dataIndex: 'role.status',
    customRender: (value) => { return value ? '启用' : '禁用' }
  },
  {
    title: '描述',
    dataIndex: 'role.description'
  }
  // {
  //   title: '操作',
  //   dataIndex: 'action',
  //   scopedSlots: { customRender: 'action' }
  // }
]

export default {
  name: 'RoleList',
  layout: 'basic-layout',
  components: {
    STable,
    PageView
  },
  data () {
    return {
      deleteId: null,
      showDelete: false,

      description: '列表使用场景：后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',
      isCreate: false,
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this),
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columnsBase,
      columns: [...columnsBase, {
        title: '操作',
        width: '220px',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      }],
      // 加载数据方法 必须为 Promise 对象

      loadDataWithPage: parameter => {
        const that = this
        return this.$domainApi.getByPageResource(0, 100, {})
          .then(res => {
            that.domains = res.data.records
            return that.$authApi.getRolesByPage(parameter.pageNo, parameter.pageSize, { ...this.queryParam })
              .then(res => {
                res.data.records.forEach(r => {
                  that.domains.forEach(domain => {
                    const p = r.permissions
                    p.forEach(pers => {
                      if (domain.id === pers.domainId) {
                        if (p.byCate === undefined) {
                          p.byCate = {}
                        }
                        if (p.byCate[domain.name] === undefined) {
                          p.byCate[domain.name] = []
                        }
                        p.byCate[domain.name].push(pers.name)
                      }
                    })
                  })
                })
                return res.data
              })
          })
      },

      loadData: parameter => {
        const that = this
        return that.$authApi.getRoles({ ...this.queryParam })
          .then(res => {
            return res
          })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },

  computed: {
    ...mapState({
      user: state => state.auth.user
    })
  },

  methods: {
    toggleStatus (record) {
      if (!record || !record.role || !record.role.id) return
      const that = this
      const params = { ...record.role }
      params.byCate = record.permissions.byCate
      params.status = !params.status

      this.$authApi.updateRole(params.id, params).then(res => {
        that.$refs.table.refresh(true)
      })
    },

    handleEdit (record) {
      this.mdl = Object.assign({}, record.role)
      this.mdl.byCate = record.permissions.byCate
      // this.mdl.permissions.byCate.forEach(permission => {
      //   permission.actionsOptions = permission.actionEntitySet.map(action => {
      //     return { label: action.describe, value: action.action, defaultCheck: action.defaultCheck }
      //   })
      // })
      if (record.role.status) {
        this.mdl.status = 'true'
      } else {
        this.mdl.status = 'false'
      }
      this.isCreate = false
      this.visible = true
    },
    newMember () {
      const length = this.data.length
      this.data.push({
        key: length === 0 ? '1' : (parseInt(this.data[length - 1].key) + 1).toString(),
        name: '',
        workId: '',
        department: '',
        editable: true,
        isNew: true
      })
    },
    handleOk () {
      const that = this
      const {
        form: { validateFields }
        // user
      } = this

      const validateFieldsKey = ['id', 'name', 'describe']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const param = this.mdl
          // param.createdTime = moment().format('YYYY-MM-DD HH:mm:ss')
          // param.updatedTime = moment().format('YYYY-MM-DD HH:mm:ss')
          // param.createdBy = user.extid || 'system'
          // param.updatedBy = user.extid || 'system'
          if (this.isCreate) {
            this.$authApi.addRole(param).then(res => {
              that.$refs.table.refresh(true)
            })
          } else {
            this.$authApi.updateRole(this.mdl.id, this.mdl).then(res => {
              that.$refs.table.refresh(true)
            })
          }
        }
        this.visible = false
      })
    },
    handleCreate () {
      this.mdl = {}
      this.isCreate = true
      this.visible = true
    },
    handleDisable (id) {
      console.log(id)
    },
    clickDelete (data) {
      const id = data && data.role && data.role.id
      if (!id) {
        return this.$notification.error({
          message: '无法删除'
        })
      }
      this.deleteId = id
      this.showDelete = true
    },
    handleDelete (id) {
      const that = this
      this.showDelete = false
      this.$authApi.delRole(id).then(res => {
        that.$refs.table.refresh(true)
        that.deleteId = null
      })
    },
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    }
  }
}
</script>

<style lang="less" scoped>
.delete-modal {
  .delete-text-content {
    display: flex;
    padding: 0 40px;

    .icon {
      font-size: 32px !important;
      margin: 6px 12px 0 0 !important;
      color: red !important;
    }
  }
}

.table-page-search-wrapper {
  .ant-form {
    .ant-row {
      .table-page-search-submitButtons,
      .ant-row.ant-form-item {
        margin-bottom: 0;
      }
    }
  }
}

.pagination-container {
  margin-bottom: 0;
}
</style>
